﻿using AduSkin.Controls.Metro;
using HsServerHa.Core.Http;
using HsServerHa.Core;
using HsServerHa.Entity.Models;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Utility.SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using HsServerHa.Utility.HttpHelper;
using Newtonsoft.Json;
using System.Configuration;
using HsServerHa.Utility;

namespace HsServerHa.UserControls.Dialog
{
    /// <summary>
    /// AddSqlData.xaml 的交互逻辑
    /// </summary>
    public partial class AddSqlData : UserControl
    {
        public AddSqlData()
        {
            InitializeComponent();
        }

        private async void btn_Setting_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(DBName.Text))
            {
                AduMessageBoxs.Show("数据库名称不能为空！");
                return;
            }

            if (string.IsNullOrEmpty(Port.Text))
            {
                AduMessageBoxs.Show("端口号不能为空！");
                return;
            }

            if (string.IsNullOrEmpty(UserId.Text))
            {
                AduMessageBoxs.Show("用户名不能为空！");
                return;
            }

            if (string.IsNullOrEmpty(UserPwd.Password))
            {
                AduMessageBoxs.Show("密码不能为空！");
                return;
            }
             

            if (string.IsNullOrEmpty(IsEnable.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "")))
            {
                AduMessageBoxs.Show("请选择是否启用！");
                return;
            }

            if (App.isMaster != null)
            {
                //查询绑定信息
                var dtBind = DbHelperSQLite.Query("select  * from MasterSlaveBind")?.Tables?[0];
                var bindList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(dtBind);
                var bindFirst = bindList?.FirstOrDefault();
                if (bindFirst == null)
                {
                    AduMessageBoxs.Show("程序配置有误，请初始化配置");
                    return;
                }
                if (string.IsNullOrEmpty( bindFirst.MasterIP)||string.IsNullOrEmpty(bindFirst.SlaveIP))
                {
                    AduMessageBoxs.Show("程序必须配置好主从才允许添加数据库操作");
                    return;
                }


                var DBConnection = ConfigurationManager.AppSettings["DBConnectionString"].ToString();
                var DBConnectionStr = DBConnection.Replace("#IPAddress#", bindFirst.MasterIP + "," + Port.Text);
                DBConnectionStr = DBConnectionStr.Replace("#DBName#", "master");
                DBConnectionStr = DBConnectionStr.Replace("#UserId#", UserId.Text);
                DBConnectionStr = DBConnectionStr.Replace("#UserPwd#", UserPwd.Password);
                //验证主
                var masterConnResult = DbHelperSQL.ConnectionTest(DBConnectionStr);
                if (!masterConnResult)
                {
                    AduMessageBoxs.Show("连接数据库失败，请检查配置");
                    return;
                }
                var DBConnectionStr1 = DBConnection.Replace("#IPAddress#", bindFirst.SlaveIP + "," + Port.Text);
                DBConnectionStr1 = DBConnectionStr1.Replace("#DBName#", "master");
                DBConnectionStr1 = DBConnectionStr1.Replace("#UserId#", UserId.Text);
                DBConnectionStr1 = DBConnectionStr1.Replace("#UserPwd#", UserPwd.Password);
                //验证从
                var slaveConnResult = DbHelperSQL.ConnectionTest(DBConnectionStr1);
                if (!slaveConnResult)
                {
                    AduMessageBoxs.Show("连接数据库失败，请检查配置");
                    return;
                }

                MessageBoxResult dr = AduMessageBox.ShowOKCancel($"你确定设置吗？", "系统提示!", "确定", "取消");
                if (dr == MessageBoxResult.OK)
                {
                    var parms = new SQLManageEntity
                    {
                        ProgramKey = GeneratePrimaryKeyIdHelper.GetPrimaryKeyId().ToString(),
                        DBName=DBName.Text,
                        Port=Port.Text,
                        UserId=UserId.Text,
                        UserPwd=UserPwd.Password, 
                        IsEnable = IsEnable.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", ""),
                        CreateTime = DateTime.Now.ToString()
                    };
                    var result = new HttpResponseResultModel<object>();
                    if (App.isMaster.Value)
                    {
                        var slavePath = $"http://{bindFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";

                        #region 上传程序数据给从机

                        result = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>(slavePath +
                       (ConfigurationManager.AppSettings["postAddSQLData"]?.ToString() ?? "postAddSQLData"), JsonConvert.SerializeObject(parms));

                        #endregion
                    }
                    else
                    {
                        var masterPath = $"http://{App.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                        #region 上传程序数据给主机

                        result = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>(masterPath +
                            (ConfigurationManager.AppSettings["postAddSQLData"]?.ToString() ?? "postAddSQLData"), JsonConvert.SerializeObject(parms));
                        #endregion
                    }
                    if (result == null)
                    {
                        AduMessageBoxs.Show("添加失败");
                        return;
                    }
                    else
                    {
                        if (result.IsSuccess)
                        {
                            SQLiteHelper.ExecuteSql($"insert into SQLManage (ProgramKey,DBName,Port,UserId,UserPwd,IsEnable,CreateTime)" +
                                    $" values('{parms.ProgramKey}','{DBName.Text}','{Port.Text}','{UserId.Text}','{UserPwd.Password}','{parms.IsEnable}','{DateTime.Now.ToString()}')");

                            AduMessageBoxs.Show("添加成功！");
                            LoggerHelper.SetInfo("新增了数据库镜像:" + JsonConvert.SerializeObject(parms), "数据库镜像管理");
                            WeakReferenceMessenger.Default.Send(new ValueChangedMessage<string>("刷新数据库数据"), "RefreshSQLManage");

                            var control = this.Parent as ContentControl;
                            Window win = Window.GetWindow(control);
                            var title = win?.Title;
                            if (title != null)
                            {
                                if (title != "HsServerHa")
                                {
                                    win.Close();
                                }

                            }
                        }
                        else
                        {
                            AduMessageBoxs.Show("添加失败");
                            return;
                        }
                    }
                }
             
            }
            else
            {
                AduMessageBoxs.Show("系统错误，请配置主从！");
                return;
            }

        }
    }
}
